package com.xkstream.client.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.WatcherAdapter;
import com.xkstream.client.camera.utils.FileUtils;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.Area;
import com.xkstream.client.entity.User;
import com.xkstream.client.http.FileUploadUtil;
import com.xkstream.client.presenter.LiveSettingContract;
import com.xkstream.client.presenter.LiveSettingPresenter;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.view.BottomPopupWindow;
import com.xkstream.client.view.CircleImageView;
import com.xkstream.client.view.ResizeLayout;
import com.xkstream.client.view.RoundImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017-9-26.
 * 直播设置
 */

public class LiveSettingActivity extends BaseActivity<LiveSettingContract.Presenter>
        implements LiveSettingContract.View {
    @BindView(R.id.ivHeader)
    CircleImageView ivHeader;
    @BindView(R.id.et_nickname)
    EditText etNickname;
    @BindView(R.id.et_roomname)
    EditText etRoomname;
    @BindView(R.id.et_location)
    TextView etLocation;
    @BindView(R.id.ivCover)
    RoundImageView ivCover;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;

    @BindString(R.string.exit_edit)
    String exitEdit;

    private String path;

    private String headerImg;
    private String converImg;

    private static final int CODE_LOCATION = 0X1001;
    private static final int CODE_HEADER_CAMERA = 0X2001;
    private static final int CODE_HEADER_PHOTO = 0X2002;
    private static final int CODE_COVER_CAMERA = 0X3001;
    private static final int CODE_COVER_PHOTO = 0X3002;

    private static final int CODE_CROP_HEADER = 0X4001;
    private static final int CODE_CROP_COVER = 0X4002;

    private Uri savePath;

    private WatcherAdapter watcher = new WatcherAdapter() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            setBtnState();
        }
    };

    private MHandler mHandler;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_live_settings);
        ButterKnife.bind(this);
        setTitle(R.string.live_settings);
        presenter = new LiveSettingPresenter(this);
        mHandler = new MHandler(this);
        initListener();
        initData();
    }

    private void initListener() {
        addTextWatcher();
    }

    private void addTextWatcher() {
        etNickname.addTextChangedListener(watcher);
        etRoomname.addTextChangedListener(watcher);
    }

    @OnClick({R.id.ivHeader, R.id.et_location, R.id.ivCover, R.id.tv_submit
            , R.id.headerBack})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivHeader:
                showPhotoSelectedDialog(1);
                break;
            case R.id.et_location:
                Intent intent = new Intent(this, AreaCodeActivity.class);
                startActivityForResult(intent, CODE_LOCATION);
                break;
            case R.id.ivCover:
                showPhotoSelectedDialog(2);
                break;
            case R.id.tv_submit:
                applyLiveSettings();
                break;
            case R.id.headerBack:
                showExitDialog();
                break;
        }
    }

    private void applyLiveSettings() {
        if (checkInput()) {
            Map<String, Object> params = new HashMap<>();
            params.put("head_icon", headerImg);
            params.put("room_name", etRoomname.getText());
            params.put("anchor_show_H5", converImg);
            params.put("cover_img", converImg);
            params.put("anchor_show_PC", converImg);
            params.put("user_code", Application.getUser().getUser_code());
            params.put("nick_name", etNickname.getText());
            presenter.applySettings(params);
        }
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(headerImg)) {
            showTopTips(R.string.header_wrong);
            return false;
        }
        if (TextUtils.isEmpty(converImg)) {
            showTopTips(R.string.cover_wrong);
            return false;
        }

        if (etNickname.getText().toString().length() < 4) {
            showTopTips(R.string.name_length);
            return false;
        }

        if (etNickname.getText().toString().length() < 2) {
            showTopTips(R.string.room_length);
            return false;
        }

        if (TextUtils.isEmpty(etLocation.getText().toString())) {
            showTopTips(R.string.choose_location);
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != -1) return;
        switch (requestCode) {
            case CODE_LOCATION:
                Area area = (Area) data.getSerializableExtra("area");
                etLocation.setText(area.getChain_name());
                setBtnState();
                break;
            case CODE_HEADER_PHOTO:
                cropImage(data.getData(), CODE_CROP_HEADER);
                break;
            case CODE_COVER_PHOTO:
                cropImage(data.getData(), CODE_CROP_COVER);
                break;
            case CODE_CROP_HEADER:
                getBitmapFromResult(data, ivHeader);
                break;
            case CODE_CROP_COVER:
                getBitmapFromResult(data, ivCover);
                break;
            case CODE_HEADER_CAMERA:
                startPhotoZoom(data, CODE_CROP_HEADER);
                break;
            case CODE_COVER_CAMERA:
                startPhotoZoom(data, CODE_CROP_COVER);
                break;
        }
    }

    private void setBtnState() {
        if (etNickname.getText().length() >= 4
                && etRoomname.getText().length() >= 2
                && etLocation.getText().length() >= 1) {
            tvSubmit.setBackgroundResource(R.drawable.btn_clickable);
        } else {
            tvSubmit.setBackgroundResource(R.drawable.btn_unclickable);
        }
    }

    private void showPhotoSelectedDialog(int index) {
        View view = View.inflate(this, R.layout.layout_choosephoto_dialog, null);
        BottomPopupWindow popupWindow = new BottomPopupWindow(this, view);
        popupWindow.show(this);
        view.findViewById(R.id.tvCamera).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    path = FileUtils.getUploadPhotoFile(this);
                    File file = new File(path);
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    startActivityForResult(intent,
                            index == 1 ? CODE_HEADER_CAMERA :
                                    CODE_COVER_CAMERA);
                    popupWindow.dismiss();
                }
        );
        view.findViewById(R.id.tvPhoto).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent,
                            index == 1 ? CODE_HEADER_PHOTO
                                    : CODE_COVER_PHOTO);
                    popupWindow.dismiss();
                }
        );
        view.findViewById(R.id.tvCancel)
                .setOnClickListener((v) -> {
                    popupWindow.dismiss();
                });
    }

    private void initData() {
        User user = Application.getUser();
        if (user.getExt_info() == null) return;
        AsyncImage.loadPhoto(this, user.getExt_info().getHead_icon(), ivHeader);
        headerImg = user.getExt_info().getHead_icon();
        converImg = user.getAnchor().getAnchor_show_H5();
        if (user.getAnchor() != null) {
            if (!TextUtils.isEmpty(user.getAnchor().getRoom_name())) {
                etRoomname.setText(user.getAnchor().getRoom_name());
            }
        }
        if (!TextUtils.isEmpty(user.getExt_info().getCountry())) {
            etLocation.setText(user.getExt_info().getCountry());
        }
        if (!TextUtils.isEmpty(user.getExt_info().getNickname())) {
            etNickname.setText(user.getExt_info().getNickname());
        }
        AsyncImage.loadPhoto(this, user.getAnchor().getAnchor_show_H5(), ivCover);
    }

    private void cropImage(Uri imageUri, int code) {
        Intent intent = new Intent("com.android.camera.action.CROP"); // 剪裁
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("scale", true);
        // 设置宽高比例
        intent.putExtra("aspectX", 400);
        intent.putExtra("aspectY", 400);
        // 设置裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("return-data", false);
        savePath = Uri.fromFile(new File(FileUtils.getUploadPhotoFile(this)));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, savePath);
        startActivityForResult(intent, code);
    }

    private void getBitmapFromResult(Intent data, ImageView iv) {

        Map<String, String> params = new HashMap<>();

        Map<String, String> textParams = new HashMap<>();
        textParams.put("bizImgPath", "show_h5");
        String result = BitmapUtil.getPathByUri4kitkat(this,
                savePath);
        params.put("iconFile", result);
        // Bitmap b = (Bitmap) data.getExtras().get("data");
        Bitmap b = BitmapFactory.decodeFile(savePath.getPath());
        showLoading();
        new Thread(() -> {
            FileUploadUtil.uploadImageFile(API.FILEUPLOAD_HOST + API.UPLOAD_FILE,
                    textParams, params, mHandler, String.valueOf(iv.getTag()));
        }).start();

        if (b != null) {
            iv.setImageBitmap(b);
        }
    }


    private void startPhotoZoom(Intent data, int code) {

        Uri uri = null;
        /*if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            //这里如果是false，就是旧版本的uri
            if (DocumentsContract.isDocumentUri(this, data.getData())) {
                String path = FileUtils.getUploadPhotoFile(this);
                uri = Uri.fromFile(new File(path));
            } else {
                uri = data.getData();
            }
        } else {
            String path = FileUtils.getUploadPhotoFile(this);
            uri = Uri.fromFile(new File(path));
        }*/

        uri = Uri.fromFile(new File(path));

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 400);
        intent.putExtra("aspectY", 400);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        savePath = Uri.fromFile(new File(FileUtils.getUploadPhotoFile(this)));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, savePath);
        startActivityForResult(intent, code);
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public void setPresenter(LiveSettingContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showResult(BaseData data) {
        if (data.getCode() == 1) {
            showTopTips(R.string.submit_success);
            mHandler.postDelayed(() -> {
                AppManager.getAppManager().finishActivity(this);
            }, 2000);
        } else {
            showTopTips(data.getMsg());
        }
    }

    private static class MHandler extends Handler {
        WeakReference<LiveSettingActivity> weakReference;

        public MHandler(LiveSettingActivity activity) {
            this.weakReference = new WeakReference<LiveSettingActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().handlerUploadMsg(msg);
                    }
                    break;
                case FileUploadUtil.FAILED:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().showTopTips(R.string.upload_failed);
                    }
                    break;

            }

        }
    }

    private void handlerUploadMsg(Message msg) {
        switch (msg.obj.toString()) {
            case "img0":
                headerImg = msg.getData().getString(FileUploadUtil.RESULT);
                break;
            case "img1":
                converImg = msg.getData().getString(FileUploadUtil.RESULT);
                break;

        }
    }

    private void showExitDialog() {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(exitEdit);
        dialog.setListener(() -> {
            finish();
        });
        dialog.show();
    }

    @Override
    public void onBackPressed() {
        showExitDialog();
    }
}
